package com.nineclock.security.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.security.mapper.UserMapper;
import com.nineclock.security.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        //查询一条数据
        User user = userMapper.selectOne(queryWrapper);
        //System.out.println(user.toString());
        //查到了,说明用户存在
        if (user != null) {
            org.springframework.security.core.userdetails.User userDetails =
                    new org.springframework.security.core.userdetails.User(
                            username, user.getPassword(),
                            AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));
            //System.out.println(userDetails.toString());
            return userDetails;
        }

        return null;

    }
}
